package com.tools.cleanmaster.utils;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;

import java.lang.ref.WeakReference;
import java.lang.reflect.Method;

public abstract class NoLeakHandler<T>  extends Handler {
    private static Class<?> sFragmentClass;
    private static Method sGetActivity;
    static {
        try {
            sFragmentClass = Class.forName("android.support.v4.app.Fragment", false,
                    Thread.currentThread().getContextClassLoader());
            sGetActivity = sFragmentClass.getDeclaredMethod("getActivity", (Class[]) null);
        } catch (Exception e) {
            e.printStackTrace();
            sFragmentClass = null;
            sGetActivity = null;
        }
    }

    private final WeakReference<T> mContext;

    public NoLeakHandler(T context) {
        mContext = new WeakReference<T>(context);
    }

    @Override
    public void handleMessage(Message msg) {
        T context = mContext.get();
        if (context != null) {
            Activity activity = null;
            if (sFragmentClass != null && sFragmentClass.isInstance(context)) {
                try {
                    activity = (Activity) sGetActivity.invoke(context, (Object[]) null);
                    if (activity == null) {
                        return;
                    }
                } catch (Exception e) {
                }
            } else if (context instanceof Activity) {
                activity = (Activity) context;
            }
            if (activity != null && activity.isFinishing()) {
                return;
            }
            processMessage(context, msg);
        }
    }

    protected abstract void processMessage(T context, Message msg);
}
